/* !
 * 数学公式解析
 */
let katex = require('./katex.js');

// 之前的正则表达式会匹配到类似<img v-sharpe="$sdas$s">里面的$...$符合，导致显示错误。现修改一下正则表达式，目前没有发现新的bug。待观察
let latexInlineRE = />[^<]*?\$(.*?)\$[^>]*?<|^[^<]*?\$(.*?)\$|\$(.*?)\$[^>]*?$/g;
let latexBlockRE = />[^<]*?\$\$(.*?)\$\$[^>]*?<|^[^<]*?\$\$(.*?)\$\$|\$\$(.*?)\$\$[^>]*?$/g;
let allImgRE = /!\[.*?\]\((.+?)\)/g;
let imgRE = /!\[.*?\]\((.+?)\)/;
let altRE = /!\[(.*?)\]\(.+?\)/;
let imgStyleRE = /(.*)\#(right|left)$/;
/**
 * 渲染latex公式，提供错误字符转化
 *
 * @param
 */

function renderLatex(latex) {
  // 去除不标准的latex字符

  let standardLatex = latex
    .replace(/<span\sclass="es__highlight">/g, '')
    .replace(/<\/span>/g, '')

    // .replace(/\s/g, '')
    .replace(/≤/g, ' \\le ')
    .replace(/≥/g, ' \\ge ')
    .replace(/≠/g, ' \\ne ')
    .replace(/×/g, ' \\times ')
    .replace(/÷/g, ' \\div ')
    .replace(/＋/g, '+')
    .replace(/∣/g, '|')
    .replace(/｜/g, '|')
    .replace(/≈/g, ' \\approx ')
    .replace(/＝/g, '=')
    .replace(/±/g, ' \\pm ')
    .replace(/．/g, '.')
    // .replace(/%/g, ' \\%')
    .replace(/：/g, ':')

    .replace(/①/g, ' \\circledOne ')
    .replace(/②/g, ' \\circledTwo ')
    .replace(/③/g, ' \\circledThree ')
    .replace(/④/g, ' \\circledFour ')
    .replace(/⑤/g, ' \\circledFire ')

    .replace(/，/g, ',')
    .replace(/（/g, '(')
    .replace(/）/g, ')')
    .replace(/\′/g, ' \\backprime ')

    .replace(/α/g, ' \\alpha ')
    .replace(/β/g, ' \\beta ')
    .replace(/π/g, ' \\pi ')
    .replace(/ρ/g, ' \\rho ')

    .replace(/！/g, '!')
    .replace(/\＞/g, '>')
    .replace(/\＜/g, '<')
    .replace(/…/g, ' \\ldots ')

    .replace(/Δ/g, ' \\triangle ')
    .replace(/△/g, ' \\triangle ')
    .replace(/∠/g, ' \\angle ')
    .replace(/⋅/g, ' \\cdot ')
    .replace(/·/g, ' \\cdot ')
    .replace(/•/g, ' \\cdot ')
    .replace(/⋆/g, ' \\ast ')
    .replace(/■/g, ' \\blacksquare ')
    .replace(/□/g, ' \\Box ')
    .replace(/°/g, ' \\circ ')
    .replace(/º/g, ' \\circ ')
    .replace(/。/g, ' \\circ ')

    .replace(/⊕/g, ' \\oplus ')
    .replace(/⊗/g, ' \\otimes ')

    .replace(/→/g, ' \\rightarrow ')
    .replace(/∅/g, ' \\varnothing ')

    .replace(/∥/g, '||')
    .replace(/\\large/g, '')
    .replace(/\\normalsize/g, '')

    // 处理减号的渲染
    .replace(/－/g, '-')
    .replace(/—/g, '-')
    .replace(/﹣/g, '-')
    .replace(/−/g, '-')

    .replace(/\\widehat/g, '\\hat');

  try {
    let renderKatex = katex.renderToString(standardLatex, {
      displayMode: true,
    });
    return renderKatex;
  } catch (e) {
    return latex;
  }
}

/**
 * 提取字符串中的latex文本 `$` 中的字符
 * $~$  $$~$$
 *
 * @param
 */
function handlerQslatex(str) {
  if (!str || str === '') {
    return str;
  }
  str = str.replace(latexInlineRE, function($1, $2) {
    return $1.replace(/\$(.*?)\$/g, function($1, $2) {
      return renderLatex($2);
    });
  });

  return str.replace(latexBlockRE, function($1, $2) {
    return $1.replace(/\$\$(.*?)\$\$/g, function($1, $2) {
      return renderLatex($2);
    });
  });
}

/**
 * 图片转化为html
 *
 * @param
 */

function imgTransform2html(str) {
  let alt = str.match(altRE);
  let imgArr = str.match(imgRE);

  if (imgArr && imgArr.length) {
    let imgOriUrl = imgArr[1];
    let floatStyle = '';
    let imgReal = '';

    imgOriUrl.replace(imgStyleRE, function($1, $2, $3) {
      imgReal = $2;
      floatStyle = $3;
    });

    if (imgReal && floatStyle) {
      return '<img src="${imgReal}" style="float:${floatStyle}">'.replace('${imgReal}', imgReal).replace('${floatStyle}', floatStyle);
    } else {
      return '<br><img src="${imgOriUrl}">'.replace('${imgOriUrl}', imgOriUrl);
    }
  }
}

/**
 * 图片解析
 *
 * @param
 */

function imageParser(image) {
  if (!image || image === '') {
    return image;
  }
  try {
    return image.replace(allImgRE, function($1, $2) {
      return imgTransform2html($1);
    });
  } catch (e) {
    return image;
  }
}

/**
 * 处理数据中不规范的字符
 *
 * @param
 */

function cleanHtml(str) {
  if (!str) {
    return str;
  }
  // img jyeoo net 图片bug 去除前后的\'
  str = str.replace(/\\\'http:\/\/img.jyeoo.net([\s\S]+?)\\\'/g, function($1, $2) {
    return $1.replace(/^\\\'|\\\'$/g, '');
  });
  return str;
}

export function preHandleNum(str) {
  // const reg = />(\d*\.)/;

  // const text = reg.exec(str);

  // if (text && text.length > 1) {
  //   const result = str.search(text[1]);

  //   const res1 = str.substring(0, result);
  //   const res2 = str.substring(result + text.length, str.length);

  //   return res1 + res2;
  // }

  // return str;

  if (/^\d+?\./.test(str)) {
    str = str.replace(/^\d+?\./, '');
  } else if (/^<(div|span)>\d+?\./.test(str)) {
    str = str.replace(/\d+?\./, '');
  }

  return str;
}

/**
 * 题目解析，包括
 * 1.解析图片
 * 2.解析latex
 * 3.替换不规范字符
 *
 * @param {String} str 题目字符串
 * @param {String} qsId 题目对应的id，用于记录错误日志
 * @param {String} html string
 */
export function questionParser(str) {
  if (!str || typeof str !== 'string') {
    return str;
  }

  str = str.replace(/http:\/\//g, 'https://');
  str = str.replace(/img\.jyeoo\.net/g, 'image.shensz.cn');
  str = str.replace(/files\.taotiba\.com/g, 'image.shensz.cn');
  str = str.replace(/\${blank}/g, '___');
  str = str.replace(/&there4;/gi, '∴ ');
  str = str.replace(/（/gi, '(').replace(/）/gi, ')'); // 视觉优化，中文括号替换成英文括号

  const res = cleanHtml(handlerQslatex(imageParser(str)));

  if (res.startsWith('<img')) {
    return `<div style="overflow: auto;">${res}</div>`;
  }

  return res;
}
